/*
** Segment.c
** load and save workspace.
*/

#include "dis6502.h"

/*
** reset segment list
*/
void SegmentReset(HWND hWnd)
{
int nSeg;

     /*
     ** free all dump buffers.
     */
     for (nSeg = 0; nSeg < MAX_SEGMENTS; nSeg++)
          {
          if (Segment[nSeg].lpDump)
               MemoryFree(Segment[nSeg].lpDump);
          if (Segment[nSeg].lpType)
               MemoryFree(Segment[nSeg].lpType);
          }

     /*
     ** clean segment array
     */
     memset(Segment, 0, sizeof(Segment));

     /*
     ** empty segment listbox
     */
     if (hWnd)
          SendDlgItemMessage(hWnd, ID_SEGMENT, LB_RESETCONTENT, 0, 0);
}

/*
** return the index of the first free segment
*/
int SegmentGetFirstFree(void)
{
int nSeg;

     for (nSeg = 0; nSeg < MAX_SEGMENTS; nSeg++)
          if (Segment[nSeg].lpDump == NULL)
               return nSeg;
     return -1;
}

/*
** return the number of segments
*/
int SegmentGetCount(void)
{
int nSeg, nCount;

     nCount = 0;
     for (nSeg = 0; nSeg < MAX_SEGMENTS; nSeg++)
          if (Segment[nSeg].lpDump)
               nCount++;
     return nCount;
}

/*
** select a new segment (update dump and disassembly window).
*/
void SegmentSelect(WORD wIndex)
{
     wDumpSegment = wIndex;
     wDumpBeginLine = wDumpEndLine = 0xFFFF;
     if (hMainWnd)
          {
          DumpChangeSegment(hMainWnd);
          DisSelectLine(hMainWnd, Segment[wDumpSegment].dwLineNumber, FALSE);
          InvalidateRect(hMainWnd, NULL, FALSE);
          }
}

/*
** selection has changed in the segment window.
*/
void SegmentSelected(void)
{
DWORD dwIndex;

     dwIndex = SendMessage(hSegmentList, LB_GETCURSEL, 0, 0);
     if ((dwIndex != LB_ERR) && (dwIndex != (DWORD) wDumpSegment))
          SegmentSelect((WORD) dwIndex);
     RefreshToolsMenu();
}

/*
** reset segment list box and add segment description
*/
void SegmentUpdate(void)
{
int nSeg;

     SendMessage(hSegmentList, LB_RESETCONTENT, 0, 0);
     for (nSeg = 0; nSeg < MAX_SEGMENTS; nSeg++)
          if (Segment[nSeg].lpDump)
               (*CompuUpdateSegment)(hSegmentList, &Segment[nSeg]);
     SendMessage(hSegmentList, LB_SETCURSEL, 0, 0L);
     wDumpSegment = NO_DUMP;
     SegmentSelected();
}
